from datetime import time
from telnetlib import EC

from appium.webdriver.common.appiumby import AppiumBy

# 页面元素定位格式
from selenium.common import NoSuchElementException, TimeoutException
from selenium.webdriver.support.wait import WebDriverWait

from 水质.utils.Logger import logger
from 水质.utils.click import allowPermission

_x = {
    "ad": "com.haogou:id/{}",
    "ext_username": "com.standards.oceanprotect:id/ext_username",
    "ext_password": "com.standards.oceanprotect.module.login.activity:id/ext_password",
    "btn_login": "com.standards.oceanprotect.module.login.activity:id/btn_login",
    "tv": "//android.widget.TextView[@text='{}']{}",
    "cs": "android.widget.{}",
    "sc": 'new UiSelector().className("{}").instance({})'
}
def cancelSavePwd(driver):
    try:
        el_allow = driver.find_element(by=AppiumBy.XPATH, value='//*[@text="取消"]')
        el_allow.click()
        logger.log("点击取消保存密码")
    except NoSuchElementException:
        pass

def input_account(self) -> None:
    allowPermission(self.driver)

    while True:
        try:
            # 等待元素出现
            el = self.driver.find_elements(by=AppiumBy.ID, value="ext_username")
            # 执行元素存在时的操作
            logger.log("登录出现，执行相应操作")
            if len(el) > 0:
                # 找到元素后跳出循环
                break
        except NoSuchElementException:
            # 元素不存在时的操作
            logger.log("元素未找到，等待...")
            allowPermission(self.driver)
            time.sleep(1)  # 等待1秒后再次尝试查找元素

    # 等待元素出现
    el = self.driver.find_elements(by=AppiumBy.ID, value="ext_username")
    if len(el) > 0:
        el[0].send_keys("kfsuperadmin")

    el = self.driver.find_elements(by=AppiumBy.ID, value="ext_password")
    if len(el) > 0:
        el[0].send_keys("123123")
    el = self.driver.find_element(by=AppiumBy.ID, value="btn_login")
    el.click()
    logger.log("点击登录，登录测试完成")
    cancelSavePwd(self.driver)
    allowPermission(self.driver)

